import WebSocket from 'ws'
import fs from 'fs/promises'
import dayjs from 'dayjs'

export default options => {
  const { address, onMessage } = {
    address: 'ws://127.0.0.1:8765',
    ...options,
  }
  const ws = new WebSocket(address)

  ws.on('open', () => {
    console.log(`已连接到服务器：${address}`)

    // 发送消息到服务器
    //   ws.send('你好，服务器！')
  })

  ws.on('message', message => {
    console.log(`收到服务器消息: ${message}`)
    if (onMessage) onMessage(message)
  })

  ws.on('close', () => {
    console.log('连接已关闭')
  })

  ws.on('error', error => {
    console.error('WebSocket 错误:', error)
  })

  return ws
}
